package com.example.educationalsystem.common.security.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.educationalsystem.common.security.pojo.SelfUserEntity;
import com.example.educationalsystem.entity.User;
import com.example.educationalsystem.service.IUserService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

/**
 * SpringSecurity用户的业务实现
 */
@Component
public class SelfUserDetailsService implements UserDetailsService {

    @Autowired
    private IUserService iUserService;

    /**
     * 查询用户信息
     * @Param username  用户名
     * @Return UserDetails SpringSecurity用户信息
     */
    @Override
    public SelfUserEntity loadUserByUsername(String username) throws UsernameNotFoundException {
        // 查询用户信息
        QueryWrapper<User> queryWrapper=new QueryWrapper<>();
        User user= iUserService.getBaseMapper().selectOne(queryWrapper.eq("user_name",username));
        if (user!= null) {
            // 组装参数
            SelfUserEntity selfUserEntity = new SelfUserEntity();
            BeanUtils.copyProperties(user,selfUserEntity);
            selfUserEntity.setPassword(user.getUserPassword());
            selfUserEntity.setUserID(user.getUserId());
            selfUserEntity.setUsername(user.getUserName());
            return selfUserEntity;
        }
        return null;
    }
}
